class Node{
    constructor(element){
        this.element = element;
        this.next = null;
    }
}

class Linked{
    constructor(){
        this.head = null;
        this.count = 0; //记录节点个数
    }

    //向链表结尾添加节点
    push(element){
        let node = new Node(element); //{element:'a',next:null}
        //1.判断链表是否为空
        if(this.head === null){
            this.head = node;
        }else{
            //查找最后一个元素 
            //如何判断是最后一个元素 ？ current.next 是否为null
            let current = this.head;
            while(current.next != null){
                //说明不是最后一个元素
                current = current.next;
            }
            current.next = node;
        }
        this.count++;
    }

    //删除指定位置的元素
    removeAt(index){
        //边界的判断
        if(index >= 0 && index <= this.count){
            let current = this.head;
            if(index === 0){
                this.head = current.next;
            }else{
                let prev = this.getElementAt(index - 1);
                current = prev.next;
                // for(let i = 0;i<index;i++){
                //     prev = current;
                //     current = current.next;
                // }
                prev.next = current.next;
            }
            this.count--;
            return current.element
        }else{
            return undefined
        }
    }

    //循环迭代链表查找指定元素
    getElementAt(index){
        let current = this.head;
        for(let i = 0;i < index;i++){
            current = current.next;
        }
        return current
    }

    //在指定的位置插入节点
    insert(element,index){
        //边界的判断
        if(index >= 0 && index < this.count){
            //1.创建节点
            let node = new Node(element);
            let current = this.head;
            //判断链表开头插入
            if(index === 0){
                node.next = current;
                this.head = node;
            }else{
                let prev = this.getElementAt(index - 1);
                node.next = prev.next;
                prev.next = node;
            }
            this.count++;
        }else{
            return false
        }
    }

    //查找指定元素的索引
    indexOf(element){
        let current = this.head;
        for(let i = 0;i<this.count;i++){
            if(element === current.element){
                return i
            }
            current = current.next;
        }
        return -1
    }

    //删掉节点
    remove(element){
        let index = this.indexOf(element);
        this.removeAt(index);
    }

    //获取链表的长度
    size(){
        return this.count;
    }

    //获取链表是否为空
    isEmpty(){
        return this.count === 0
    }
    
    //获取首个节点
    getHead(){
        return this.head
    }
    
}

let link = new Linked();

link.push('a')

link.push('b')

// link.insert('c',1);

// link.remove('b');

// console.log(link.removeAt(1));

// console.log(link.indexOf('p'))

console.log(link.getHead());